package com.lxyk.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lxyk.pojo.Customer;
import com.lxyk.pojo.History;
import com.lxyk.pojo.MainMenu;
import com.lxyk.pojo.Worker;
import com.lxyk.service.CustomerService;
import com.lxyk.service.HistoryService;
import com.lxyk.service.WorkerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * @ClassName HistoryController
 * @Description TODO
 * @Author FJQ
 * @Date 2022/10/25 9:28
 * @Version 1.0
 **/
@Controller
@RequestMapping("/history")
public class HistoryController {

    @Autowired
    private HistoryService historyService;
    @Autowired
    private CustomerService customerService;
    @Autowired
    private WorkerService workerService;
    @Autowired
    private RedisTemplate redisTemplate;


    @RequestMapping("/listHis")
    public String listHistory(Model model,@RequestParam Map<String, Object> map, @RequestParam(required = false,defaultValue = "1",value = "pageNum" )Integer pageNum,
                              @RequestParam(defaultValue = "10",value = "pageSize" )Integer pageSize) {
        if (pageNum <= 0 || pageNum.equals("") || pageNum == null){
            pageNum = 1;
        }
        if (pageSize <= 0 || pageSize.equals("") ||pageSize == null){
            pageSize = 10;
        }
        PageHelper.startPage(pageNum,pageSize);
        PageInfo<History> pageInfo = historyService.listHistory(map,pageNum, pageSize);
        model.addAttribute("pageInfo",pageInfo);
        return "historyList";
    }

    @RequestMapping("/preSaveHis")
    public  String preSaveHistory(Model model){
        List<Customer> custList = customerService.listCustomer();
        List<Worker> workerList = workerService.listWorker();
        model.addAttribute("custList",custList);
        model.addAttribute("workerList",workerList);
        return "historySave";
    }

    @PostMapping("/saveHis")
    public String saveHistory(Integer workerId,Integer custId,History history) {

        Worker worker = new Worker();
        worker.setWid(workerId);
        Customer cust = new Customer();
        cust.setCid(custId);
        history.setWorker(worker);
        history.setCustomer(cust);
        historyService.addHistory(history);

        //清空redis
        redisTemplate.delete("mainMenu");
        //查询再次设置到redis进行排序
        List<MainMenu> mainMenu = new ArrayList<>();
        List<MainMenu> list = new ArrayList<>();
        Map<Integer, Integer> map = new HashMap<>();
        historyService.listHistory().forEach(h ->{
            map.put(h.getWorkerId(),map.getOrDefault(h.getWorkerId(),0)+h.getSendWaterCount());
        });
        workerService.listWorker().forEach(e -> {
            MainMenu main = new MainMenu();
            main.setWorkerName(e.getWorkerName());
            Integer count = map.get(e.getWid());
            main.setSendWaterCount(count == null ? 0 : count);
            list.add(main);
        });

        Collections.sort(list, (o1,o2) ->{
            if(o1.getSendWaterCount() > o2.getSendWaterCount()){
                return 1;
            }else if (o1.getSendWaterCount()  < o2.getSendWaterCount()){
                return -1;
            }else {
                return 0;
            }
        });
        if (list.size() < 12){
            mainMenu.addAll(list);
        }
        for (int i = list.size() - 12; i < list.size(); i++) {
            mainMenu.add(list.get(i));
        }
        redisTemplate.opsForList().leftPushAll("mainMenu",mainMenu);
        return "redirect:/history/listHis";
    }


    @RequestMapping("/preUpdateHis/{hid}")
    public String preUpdateHistory(@PathVariable("hid") Integer hid, Model model) {
        List<Customer> custList = customerService.listCustomer();
        List<Worker> workerList = workerService.listWorker();
        History history = historyService.getHistoryById(hid);
        // 将查询的数据渲染到前端页面，完成数据的回显
        model.addAttribute("custList",custList);
        model.addAttribute("workerList",workerList);
        model.addAttribute("history",history);
        // 跳转到“修改送水历史”页面
        return "historyUpdate";
    }


    @RequestMapping(value="/updateHis",method=RequestMethod.POST)
    public String updateHistory(Integer workerId,Integer custId,History history) {

        Worker worker = new Worker();
        worker.setWid(workerId);

        Customer customer = new Customer();
        customer.setCid(custId);
        history.setCustomer(customer);
        history.setWorker(worker);
        // 修改送水历史，返回受影响行数
        historyService.updateHistory(history);
        return "redirect:/history/listHis";
    }


    @RequestMapping("/batchDeleteHistory")
    @ResponseBody
    public String deleteHistory(String idList){
        int rows = historyService.batchDeleteHistory(idList);
        if (rows > 0){
            return "OK";
        }else{
            return "Error";
        }
    }


}
